<template>
  <div class="product-edit-form bbx-normal-page-box">
    <div class="flex-x normal-title-1">
      <div class="flex-1">
        <div class="flex-1" style="font-size: 0;">
          
        </div>
      </div>
      <FormCellChange
        class="mar-r-8"
        :count="formCellCount"
        @update="
          e => {
            formCellCount = e;
          }
        "
      ></FormCellChange>
      <el-button v-if="productRegisterId" type="plain-third" @click="back">
        {{$t('common.base.back')}}
      </el-button>
      <el-button type="primary" @click="submit()" :loading="pending">
        {{$t('common.base.confirm')}}
      </el-button>
    </div>
    <div :class="['flex-1 scroll-y', formCellCount > 1 ? 'bbx-normal-form-builder-cell' : '']">
      <form-builder
        ref="form"
        :fields="fields"
        :value="value"
        :is-edit="isEdit"
        mode="productRegister"
        class="bbx-cell-form-builder"
        @update="update"
        :form-cell-count="formCellCount"
      >
      </form-builder>
    </div>

    <!-- :default-address="selectedAddress" -->
  </div>
</template>

<script>
import * as FormUtil from '@src/component/form/util';

import {
  getProductInfo,
  // checkRepeat
} from '@src/api/productRegisterApi';
import {
  getConfig
} from '@src/api/ProductV2Api';
import { cloneData } from "@src/api/ProductV2Api";
import _ from "lodash";
import { getFieldValue2string } from '@service/TaskService.ts'
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import FormCellChange from '@src/component/compomentV2/FormCellChange/index.vue';

export default {
  name: "product-register-edit-form",
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Object,
      required: true,
    },
    productRegisterId: {
      type: String,
      default: '',
    },
    pending:{
      type:Boolean,
      default:false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    relationProductData: {
      type: Object
    }
  },
  inject: ['initData'],
  components:{FormCellChange,},
  data() {
    return {
      template: [],
      serialNumberExist: false,
      catalog:[],
      catalogTree:[],
      ifRegisterValid: true, // 为false时，通过产品注册标识获取产品失败不做提示，可提交
      formCellCount:1,
    };
  },
  mounted(){
    const existCatalog=this.fields.find(item=>item.fieldName==="catalogId");
    if(existCatalog) this.getTreeList();
    this.getConfig()
  },
  methods: {
    // 返回
    back(){
      let fromId = window.frameElement?.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_register_view_${this.productRegisterId}`,
      //   title: '产品注册详情',
      //   close: true,
      //   url: `/product/register/detail/${this.productRegisterId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductRegisterDetail,
        key: this.productRegisterId,
        params: 'noHistory=1',
        fromId
      })
    },
    getConfig() {
      getConfig({
        configCode: [
          'REGISTER_WITHOUT_SYS',
        ]
      }).then(res => {
        if (res.status !== 0) return
        this.ifRegisterValid = !res.data[0]?.isOpen
      })
    },
    validationCatalog(){
      const catalogIdItem=this.fields.find(item=>item.fieldName==='catalogId');
      let isNull;
      if(catalogIdItem){
        isNull=!catalogIdItem.isNull;
      }
      return new Promise((resolve, reject) => {
        if(!this.catalog.length && isNull) {
          return resolve(this.$t('common.placeholder.selectProductType'));
        } 
        resolve(null);
      })
    },
    catalogInput(value){
      const length=value.length;
      this.catalog=value;
      const field=this.fields.find(item=>item.fieldName === 'catalogId');
      this.update({
        field,
        newValue:{
          id: length ? value[length - 1] : '',
          fromType: 'inputEvent'
        }
      })
    },
    initCatalog(){
      const keys=Object.keys(this.value);
      const catalogKey=keys.find(key=>key==='catalogId');
      if(catalogKey){
        const catalogId=this.value[catalogKey];
        const id=Array.isArray(catalogId)?catalogId[0]?.id:catalogId.id;
        let treeArr=[];
        this.flat(this.catalogTree,treeArr);
        if(id) this.getCatalogParents(id,treeArr,this.catalog);
      }
    },
    // 拉平产品类型树
    flat(tasks,arr){
      tasks.forEach(item=>{
        arr.push(item);
        if(item.tasks && item.tasks.length){
          this.flat(item.tasks,arr);
        }
      });
    },
    // 获取产品类型id及其父级
    getCatalogParents(id,treeArr,catalogArr){
      catalogArr.unshift(id);
      const item=treeArr.find(t=>t.id===id);
      if(item && item.parentId){
        this.getCatalogParents(item.parentId,treeArr,catalogArr);
      }
    },
    async getTreeList(){
      try{
        const {code,message,result}=await cloneData();
        if(code===0){
          this.deleteEmpty(result);
          this.catalogTree=result;
          this.initCatalog();
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.requestError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty(list){
      list.forEach(item=>{
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    // submitChooseQrcode(){
    //   this.$emit('submitChooseQrcode');
    // },
    submit(){
      this.$emit('submit');
    },
    updateValue(value) {
      let nv = null;
      const register = value[0];

      this.fields.forEach((f) => {
        nv = f.isSystem
          ? register[f.fieldName]
          : register.attribute[f.fieldName];

        if (!!nv) {
          this.update({
            field: f,
            newValue: nv,
          });
        }
      });
    },

    genPlaceholder(field) {
      return FormUtil.genPlaceholder(field);
    },

    findItem(fieldName) {
      return this.$refs.form?.$children?.find(v => (v.forId?.split('form_')[1] === fieldName))
    },

    // 确认重复（发现src/util/validator.js文件中已有现成的判断重复的逻辑，此处暂时保留，可删）
    // checkRepeat: _.debounce(function (fieldList) {
    //   let para = {
    //     fieldList,
    //     id: this.productRegisterId
    //   }
    //   return checkRepeat(para).then(res => {
    //     if (res.result?.length) {
    //       res.result?.forEach(({fieldName, displayName}) => {
    //         let formItem = this.$refs.form?.$children?.find(v => (v.forId?.split('form_')[1] === fieldName))
    //         formItem.errMessage = `${displayName}已存在`
    //       })
    //       return false
    //     }
    //   })
    // }, 1000),
    // 获取产品信息
    getProductInfo: _.debounce(function (registerValue) {
      let para = {
        registerValue
      }
      return getProductInfo(para).then(res => {

        if (res.code !== 0) {
          if (!this.ifRegisterValid) return
          const fieldName = this.fields.find(v => v.isRegister)?.fieldName
          let formItem = fieldName ? this.findItem(fieldName) : null
          if (formItem) {
            formItem.errMessage = res.message
          } else {
            this.$platform.notification({
              title: this.$t('common.label.getProductMessageFailed'),
              message: res.message || '',
              type: 'error',
            })
          }
          this.errHandle(res.errMessage || '')
          return
        }
        let data = res.result || {}
        let relationProductData = {
          attribute: {}
        }
        this.fields.forEach(field => {
          if(field.formType === 'relationProduct') {
            let fieldName = field.fieldName
            let fieldNameMap = field.setting.fieldName
            let setObj = fieldName.startsWith('field_') ? relationProductData.attribute : relationProductData
            let setData = fieldNameMap.startsWith('field_') ? (data.attribute || {})[fieldNameMap] : data[fieldNameMap]

            setObj[fieldName] = setData || ''
          }
        })
        let relationFields = this.fields.filter(field => field.formType === 'relationProduct')
        // 数据备份
        this.$emit('updateRelationProductData', relationProductData)

        this.relationFieldUpdateHandler(data, relationFields)
        this.value.catalogId = data.catalogId
        this.value.productChecked = true
      }).catch(err => {
        console.log(err)
        this.errHandle()
      })
    }, 1000),

    errHandle(errMsg) {
      if (!this.ifRegisterValid) return
      let relationFields = this.fields.filter(field => field.formType === 'relationProduct')
      if (this.value.productChecked) { // 原先验证成功的，就清一下
        this.$emit('updateRelationProductData', {
          attribute: {}
        })
        this.relationFieldUpdateHandler({}, relationFields)
        this.value.catalogId = ''
      }
      this.value.productChecked = false
      this.value.productCheckedMsg = errMsg || this.$t('common.label.getProductMessageFailed')
    },

    /** 
     * @description 关联显示项字段更新处理
    */
    relationFieldUpdateHandler(info, relationFields = []) {
      let fieldName = '';
      let formType = '';
      let fieldValue = '';

      relationFields.forEach(relationField => {
        fieldName = relationField?.setting?.fieldName;
        formType = relationField?.setting?.formType;

        let valueStr = getFieldValue2string(info, fieldName, formType, [{
          fieldName,
          formType,
          setting: relationField?.setting
        }], false)
        fieldValue = valueStr;

        this.update({ field: relationField, newValue: fieldValue });
      })
    },


    async update({ field, newValue, oldValue, fromType }) {
      let { fieldName, displayName } = field;
      // if (newValue && field.setting.isRepeat) {
      //   this.checkRepeat([{
      //     fieldName,
      //     displayName,
      //     fieldValue: newValue
      //   }])
      // }
      if (newValue && field.isRegister) {
        this.getProductInfo(newValue)
      }
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      let value = this.value;

      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },
    // 在产品类型选项中查找对应的值
    searchCatalogIds (catalogOption, catalogId) {
      for(let catalog of catalogOption) {
        if(catalog.tasks) {
          // 递归寻找值
          let res = this.searchCatalogIds(catalog.tasks, catalogId)
          // 子级找到值，就把这级的id加进去
          if (res) {
            res.unshift(catalog.id)
            return res
          }
        } else if (catalog.id === catalogId) {
          // 找到值并返回
          return [catalogId]
        }
      }
    },
    validate() {
      return this.$refs.form
        .validate(false)
        .then((valid) => {
          return valid;
        })
        .catch((err) => console.error(err));
    },
    searchTemplate(params) {
      // params has three properties include keyword、pageSize、pageNum.
      const pms = params || {};

      return getProductTemplateList(pms)
        .then((res) => {
          if (!res || !res.list) return;
          if (res.list) {
            res.list = res.list.map((template) =>
              Object.freeze({
                label: template.name,
                value: template.id,
                ...template,
              })
            );
          }
          return res;
        })
        .catch((e) => console.error(e));
    },
  }
};
</script>

<style lang="scss">
.margin-left-10 {
  margin-left: 10px;
}
.product-template-option {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 500;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;

    & > span {
      width: 50%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;    

      & > label {
        padding: 0;
        width: 70px;
      }
      & > span {
        @include text-ellipsis();
      }
    }
  }
}

.form-item-control {
  .form-customer-select {
    display: flex;

    .base-select-container {
      flex: 1;
    }

    .btn {
      width: 60px;
      height: 32px;
      line-height: 22px;
    }
  }
}

.base-modal-body {
  .form-builder {
    width: 540px;
  }
}
.customer-item {
  * {
    margin: 0;
  }
  padding: 10px 0;
  h3 {
    font-size: 14px;
    font-weight: 600;
    line-height: 24px;
  }

  p {
    display: flex;
    justify-content: space-between;
    line-height: 24px;
    flex-wrap: wrap;
    flex-flow: column;

    & > span {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      font-size: 12px;
      color: #666666;
      padding-right: 10px;

      & > label {
        padding: 0;
        width: 60px;
      }
      & > span {
        @include text-ellipsis();
      } 
    }
  }
}

// .customer-item {
//   h3 {
//     font-size: 14px;
//     margin: 0;
//     padding-left: 10px;
//   }

//   p {
//     display: flex;
//     margin: 0;
//     span {
//       label {
//         display: inline-block;
//         width: auto;
//       }

//       span {
//         margin-right: 10px;
//       }
//     }
//   }
// }

.customer-linkman {
  display: flex;
  margin: 0;

  span {
    label {
      display: inline-block;
      width: auto;
    }

    span {
      margin-right: 10px;
    }
  }
}
</style>

<style lang="scss" scoped>

.customer-bind{
  ::v-deep .form-item-control{
    display: flex;
    align-items: center;
    margin-bottom: 13px;
  }

  .customer-bind-radio-group{
   display: flex;
   label{
     padding-left: 0;
     width:60px;
   }
  }   
}
.tip{
    font-size:12px;
    color:#8c8c8c;
    margin-top:4px ;
  }

@mixin title-class {
  height: 48px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  font-weight: 600;
}
.normal-title-1 {
  // @include title-class();
  padding: 12px 10px;
  height: auto;
  font-size: 20px;
  border-bottom: 1px solid #f4f7f5;
}
.normal-title-2 {
  @include title-class();
  padding: 0 12px;
  font-size: 16px;
}
.normal-title-2-bord-bottom {
  @extend .normal-title-2;
  border-bottom: 1px solid $color-border-l1;
  margin-bottom: 20px;
}
.product_error {
  color: #f56c6c;
  margin-left: 110px;
  display: inline-block;
  transform: translateY(-8px);
  font-size: 12px;
}
</style>
